package org.biz.modules.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.biz.common.Result;
import org.biz.modules.entity.LoginUserVO;
import org.biz.modules.entity.SysRole;
import org.biz.modules.entity.SysUser;
import org.biz.modules.service.SysRoleService;
import org.biz.modules.service.SysUserService;
import org.biz.util.UserContext;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Resource
    private SysUserService sysUserService;
    @Resource
    private SysRoleService sysRoleService;
    @Value("${data.year}")
    private String dataYear;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LoginUserVO vo = new LoginUserVO();
        SysUser user;
        List<SysRole> roleList = null;
        user = sysUserService.getOne(new QueryWrapper<SysUser>()
                .lambda()
                .eq(SysUser::getMobile, username)
                .eq(SysUser::getDataYear, dataYear)
        );
        if (user == null) {
            // **取出身份证号**
            String idCard = UserContext.getIdCard();
            if (StringUtils.isBlank(idCard)) {
                throw new UsernameNotFoundException("身份证信息缺失，无法验证用户身份");
            }
            user = sysUserService.getOne(new QueryWrapper<SysUser>()
                    .lambda()
                    .eq(SysUser::getName, username)
                    .eq(SysUser::getIdCard, idCard)
                    .eq(SysUser::getDataYear,dataYear)
            );
        }
        if (user == null) {
            throw new UsernameNotFoundException("该用户名用户不存在");
        }
        roleList = sysRoleService.getRoleListByUserId(user.getId());
        //普通用户=姓名+身份证，置空禁用密码登录
        if (CollectionUtils.isEmpty(roleList)) {
            user.setPwd(null);
        }
        vo.setSysUser(user);
        vo.setRoleList(roleList);
        return vo;
    }
}
